import appList from '@/appList.js'

export default {
  namespaced: true,
  state:()=>({
    desktopEl:null,
    appsList:null,
    appsMap:null,
    activeApps: [],
  }),
  mutations: {
    SET_DESKTOP_El: (state,el)=>{
      state.desktopEl = el
    },
    SET_APPS_LIST: (state,appsList)=>{
      state.appsList = appsList
    },
    SET_APPS_MAP: (state,appsMap)=>{
      state.appsMap = appsMap
    },
    LAUNCH_APP: (state,id)=>{
      if(state.activeApps.findIndex(i=>i.id === id) > -1) return
      const {$el} = state.appsMap.get(id)
      const app = state.appsList.find(i=>i.id === id)
      state.activeApps.push(app)
      state.desktopEl.appendChild($el)
    },
    CLOSE_APP: (state,id)=>{
      const {$el} = state.appsMap.get(id)
      const index = state.activeApps.findIndex(i=>i.id === id)
      state.activeApps.splice(index,1)
      state.desktopEl.removeChild($el)
    },
    TOGGLE_APP_VISIBILITY: (state,id)=>{
      const app = state.appsMap.get(id)
      app.$children[0].onToggleVisibility()
    }
  },
  actions:{
    initApps: async ({commit})=>{
      let appsMap = new Map()
      let appsList = []
      for(let i of appList){
        const module = await i.module()
        appsMap.set(i.id,module.default)
        appsList.push({
          id: i.id,
          label: i.label,
          icon: i.icon
        })
      }
      console.log('appsMap',appsMap)
      commit('SET_DESKTOP_El',document.getElementById('jay-desktop-main'))
      commit('SET_APPS_LIST',appsList)
      commit('SET_APPS_MAP',appsMap)
    }
  },
  getters: {

  }
}